package com.example.controller;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONException;
import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.example.entity.Count;
import com.example.entity.User;
import com.example.mapper.UserMapper;
import com.example.mapper.UserRepository;
import com.example.service.CountService;
import com.example.units.ApiResponse;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpStatus;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.bson.json.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.*;

@Slf4j
@RestController

public class UserController {

    @Autowired
    UserMapper userMapper;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    private CountService countService;

    @GetMapping("/test")
    public String test() {
        System.out.println("1111");
        return "test";
    }

    String userCollection = "user";
    @Autowired
    UserRepository userRepository;

    @PostMapping("/register")
    public ApiResponse register(@RequestBody User entity) {
        log.info("register user: {}", entity);
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("email", entity.getEmail());
//        User user = userMapper.selectOne(queryWrapper);
//        if (user != null) {
//            return ApiResponse.failure("已存在此用户");
//        }else {
//            entity.setId(UUID.randomUUID().toString());
//            userMapper.insert(entity);
//            return ApiResponse.success();
//        }
        log.info("register user: {}", entity);

        // 检查邮箱是否已存在
        User existingUser = userRepository.findByEmail(entity.getEmail());
        if (existingUser != null) {
            return ApiResponse.failure("已存在此用户");
        }

        // 生成 UUID 并保存
        entity.setId(UUID.randomUUID().toString());
        entity.setLocalDateTime(System.currentTimeMillis());
        userRepository.save(entity); // MongoDB 保存操作[3,5](@ref)
        return ApiResponse.success();


    }

    @PostMapping("/login")
    public ApiResponse login(@RequestBody User entity) {
        log.info("login user: {}", entity);
//        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
//        queryWrapper.eq("email", entity.getEmail()).eq("password", entity.getPassword());
//        User user = userMapper.selectOne(queryWrapper);
//        if (user != null) {
//            return ApiResponse.success(user);
//        }else{
//            return ApiResponse.failure("用户或密码错误！！");
//        }
        User byEmailAndPassword = userRepository.findByEmailAndPassword(entity.getEmail(), entity.getPassword());
        if (byEmailAndPassword != null) {
            byEmailAndPassword.setLocalDateTime(System.currentTimeMillis());
            userRepository.save(byEmailAndPassword);
            return ApiResponse.successData(byEmailAndPassword);


        } else {
            return ApiResponse.failure("用户或密码错误！！");
        }


    }
    String countCollection = "count";
    @PostMapping("/editInfo")
    public ApiResponse editInfo(@RequestBody String body) {
        log.info("editInfo: {}", body);
        JSONObject jsonObject = JSON.parseObject(body);
        String email = jsonObject.getString("email");
//        List<User> userByEmail = userRepository.findUserByEmail(email);
//        if(userByEmail.size() > 0){
//            return ApiResponse.failure("有相同用户名称");
//        }
        String phone = jsonObject.getString("phone");
        String bio = jsonObject.getString("bio");
//        String _id = jsonObject.getString("_id");

        User userById = userRepository.findUserById(email);
//        List<JSONObject> countList = mongoTemplate.find(new Query().addCriteria(Criteria.where("creater").is(userById.getEmail())), JSONObject.class,countCollection);
//        countList.stream().forEach(count -> {
//            Update update = new Update();
//            update.set("creater",email);
//            mongoTemplate.upsert(Query.query(Criteria.where("id").is(count.getString("id"))),update,countCollection);
//        });
//
//        userById.setEmail(email);
        userById.setPhone(phone);
        userById.setBio(bio);
        userRepository.save(userById);

        return ApiResponse.success();
    }
    @PostMapping("/setPreFund")
    public ApiResponse setPreFund(@RequestBody String body) {
        log.info("setPreFund: {}", body);
        JSONObject jsonObject = JSON.parseObject(body);
        String email = jsonObject.getString("email");
        double preFund = jsonObject.getDouble("preFund");
        User userById = userRepository.findByEmail(email);
        if (userById != null) {
            userById.setPreFund(preFund);
        }
        userRepository.save(userById);
        return ApiResponse.success();
    }

    @GetMapping("/getPreFund/{email}")
    public ApiResponse getPreFund(@PathVariable String email) {
        log.info("getPreFund for email: {}", email);
        User user = userRepository.findByEmail(email);
        if (user != null) {
            return ApiResponse.successData(user.getPreFund());
        } else {
            return ApiResponse.failure("用户不存在");
        }
    }

    @PostMapping("/verifyLogin")
    public ApiResponse verifyLogin(@RequestBody String body) {
        log.info("login verifyLogin body: {}", body);
        boolean isverify = true;
        User byEmail=new User();
        try {


            JSONObject email = JSONObject.parseObject(body);
            String emailStr = email.getString("email");
            Query query = new Query();
            query.addCriteria(Criteria.where("email").is(emailStr));
            long THIRTY_DAYS_IN_MILLIS = 30L * 24 * 60 * 60 * 1000;  // 30天 = 2,592,000,000 毫秒
//            long THIRTY_DAYS_IN_MILLIS =  60 * 1000;  // 30天 = 2,592,000,000 毫秒
            byEmail = userRepository.findByEmail(emailStr);
            long lastLoginMillis = byEmail.getLocalDateTime();
            if (byEmail != null) {
                if (!((System.currentTimeMillis() - lastLoginMillis) <= THIRTY_DAYS_IN_MILLIS)) {

                    isverify = false;
                }
            } else {
                isverify = false;
            }


        } catch (Exception e) {
            e.printStackTrace();
            return ApiResponse.failure(e.getMessage());
        }
        log.info("login verifyLogin isverify: {}", isverify);
        return isverify ? ApiResponse.successData(byEmail.getId()): ApiResponse.failure("重新登录");

    }
}